package com.yangmf.auto_message_handle.pojo.entity;

import com.yangmf.auto_message_handle.constant.Message_Type;
import com.yangmf.auto_message_handle.constant.Other_constant;
import com.yangmf.auto_message_handle.utils.Deskutil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Component
@Slf4j
public class DataManager {
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private  final  ConcurrentHashMap<String, Event> dataMap = new ConcurrentHashMap<>();

    @Autowired
    private Deskutil deskutil;

    // 所有公共方法都自己管理锁，不依赖其他方法

    public void addData(String key, Object data, Integer data_type, Integer Message_id) throws IOException {

synchronized (dataMap) {
    try {


        if (dataMap.containsKey(key)) {
            log.info("数据已存在");
            if (data_type == Message_Type.TEXT_MESSAGE) {
                dataMap.get(key).getEventContent().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.TEXT_MESSAGE)
                                .eventType(dataMap.get(key).getEventType())
                                .build()

                );
                if (Message_id != Other_constant.FOWARD_IGORE_ID)
                    dataMap.get(key).getEvent_message_id().add(Message_id);
                log.info("添加数据成功");
            } else if (data_type == Message_Type.IMAGE_MESSAGE) {
                log.info("添加图片数据");
                dataMap.get(key).getEventPic().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.IMAGE_MESSAGE)
                                .eventType(dataMap.get(key).getEventType())
                                .build()

                );
                if (Message_id != Other_constant.FOWARD_IGORE_ID)
                    dataMap.get(key).getEvent_message_id().add(Message_id);
                log.info("添加数据成功");
            } else if (data_type == Message_Type.FILE_MESSAGE) {
                log.info("添加文件数据");
                dataMap.get(key).getEventFile().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.FILE_MESSAGE)
                                .eventType(dataMap.get(key).getEventType())
                                .build()
                );
                if (Message_id != Other_constant.FILE_IGORE_ID)
                    dataMap.get(key).getEvent_message_id().add(Message_id);
                log.info("添加文件成功");
            } else if (data_type == Message_Type.TENCENT_DOC_MESSAGE) {
                log.info("添加文档数据");
                dataMap.get(key).getEventDoc().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.TENCENT_DOC_MESSAGE)
                                .eventType(dataMap.get(key).getEventType())
                                .build()
                );
                if (Message_id != Other_constant.FOWARD_IGORE_ID)
                    dataMap.get(key).getEvent_message_id().add(Message_id);
                log.info("添加数据成功");


            }
        } else {//不存在则初始化事件类


            /**
             * TODO:
             * 要处理获取事件的类型和
             * TODO:学科--需要添加在数据库动态获取学科和提示词
             */
            //获取学科
            // String event_subject = deskutil.getResponse(data+"帮我获取这个事件是哪个学科类型的，如果不能获取到请返回false五个字");

            //获取事件类型
            String event_type1 = deskutil.getResponse("事件为:"+data + "帮我获取这个事件是哪个类型，如果是比赛则返回1这个数字,如果是志愿则返回2这个数字，如果是作业则返回3，如果是通知则返回4，如果是其他的则返回5，你的推导过程不要返回给我，请确定你返回的消息内容只能有前面几个数字");

            //去掉前后空格和引号
            log.info("开始创建事件{}", key);

            Integer event_type = Integer.parseInt(event_type1.trim().replace("\"", ""));
            log.info("事件类型为{}", event_type);
            String event_subject = null;


            Event event = new Event();
            event.setEventName(key);
            event.setEventUuid(UUID.randomUUID().toString());
            event.setStartTime(LocalDateTime.now());
            event.setEventContent(new ArrayList<>());
            event.setEventPic(new ArrayList<>());
            event.setEventFile(new ArrayList<>());
            event.setEventDoc(new ArrayList<>());
            //加入id
            ArrayList<Integer> objects = new ArrayList<>();

            if (Message_id != Other_constant.FILE_IGORE_ID && Message_id != Other_constant.FOWARD_IGORE_ID)
                objects.add(Message_id);

            event.setEvent_message_id(objects);

            if (event_type != null)
                event.setEventType(event_type);
            if (event_subject != null)
                event.setEventSubject(event_subject);
            if (data_type == Message_Type.TEXT_MESSAGE) {

                event.getEventContent().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.TEXT_MESSAGE)
                                .eventType(event_type)
                                .build()
                );

            } else if (data_type == Message_Type.IMAGE_MESSAGE) {

                event.getEventPic().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.IMAGE_MESSAGE)
                                .eventType(event_type)
                                .build());

            } else if (data_type == Message_Type.FILE_MESSAGE) {

                event.getEventFile().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.FILE_MESSAGE)
                                .eventType(event_type)
                                .build()
                );

            } else if (data_type == Message_Type.TENCENT_DOC_MESSAGE) {

                event.getEventDoc().add(
                        Mesg.builder()
                                .content((String) data)
                                .isDelete(0)
                                .createTime(LocalDateTime.now())
                                .messageType(Message_Type.TENCENT_DOC_MESSAGE)
                                .eventType(event_type)
                                .build()
                );
            }
            dataMap.put(key, event);

            log.info("创建事件成功");
        }


    } finally {

    }
}
    }

    public Set<String> getKeys() {


            return new HashSet<>(dataMap.keySet());

    }

    public String Inmap(String key) throws IOException {


        synchronized (dataMap) {

            if (dataMap.isEmpty()) {
                log.info("数据为空");
                return null;
            }

            // 创建key的副本进行遍历
            Set<String> keys = new HashSet<>(dataMap.keySet());
            for (String existingKey : keys) {
                // 这里注意：deskutil.getResponse可能是耗时操作，考虑优化
                String response = deskutil.getResponse("帮我判断一下传入的两句话是不是属于同一事件，如果是则只返回true四个字，如果传入的一句话中内容包含另一句话，或者两句话的关键词一样，例如'关于劳动教育学时申请提醒'和‘劳动教育实施方案’这种关键词相同的，也返回true四个字，否则则返回false,结果只能是true或者false,不要给我其他的例如分析过程" + existingKey + "和" + key);
                log.info("{}和{}判断结果：{}", existingKey, key, response);
                String cleanedResponse = response.trim().replaceAll("^\"|\"$", "");
                if (cleanedResponse.equals("true")) {
                    return existingKey;
                }
            }
            return null;
        }
        }

        public ConcurrentHashMap<String, Event> getDataMap () {
            return dataMap;
        }

        public void clearDataMap () {
            dataMap.clear();
        }
        public Boolean removeData (String key){
            Lock readLock = rwLock.readLock();
            readLock.lock();
            try {
                return dataMap.remove(key) != null;
            } finally {
                readLock.unlock();
            }
        }

    // 其他方法...
}